<?php

namespace core;
class lss{
    public static $classMap = array();#用于判断类是否存在，节约性能
    public $assign;#用于判断类是否存在，节约性能

    /**
     * 运行控制器和方法
     * @throws \Exception
     */
    static public function run(){
        \core\lib\log::init();

        $route =new \core\lib\route();
        $ctrlClass = $route->ctrl;
        $action = $route->action;
        $ctrlFile = APP.'/controller/'.$ctrlClass.'.php';#控制器文件
        $ctrlClass1 = '\\'.MODULE.'\controller\\'.$ctrlClass;
        if (is_file($ctrlFile)){
            include $ctrlFile;
            $ctrl = new $ctrlClass1();
            $ctrl->$action();
            \core\lib\log::log('ctrl:'.$ctrlClass.'  '.'action:'.$action);
        }else{
            throw new \Exception('找不到控制器'.$ctrlClass);
        }

    }

    /**
     * 基础类，自动加载类库
     * @param $class
     * @return bool
     */
    static public function load($class){
        //new \core\route();
        //$class = '\core\route';
        //LSS.'/core/route.php';
//        var_dump($class);
        if (isset($classMap[$class])){#类存在，即不引用类
            return true;
        }else{
            $class = str_replace('\\','/',$class);
            $file = LSS.'/'.$class.'.php';
            if (is_file($file)){
                include $file;#引用文件
                self::$classMap[$class] = $class;
            }else{
                return false;
            }
        }
    }

    /**
     * 变量名替换
     * @param $name
     * @param $value
     */
    public function assign($name,$value){
        $this->assign[$name] = $value;
    }

    /**
     * 显示视图
     * @param $file
     */
    public function display($file){
        /*$file = APP.'/views/'.$file;
        if (is_file($file)){
            extract($this->assign);#从数组中将变量导入到当前的符号表
            include $file;
        }*/
        $file1 = APP.'/views/'.$file;
        if (is_file($file1)){
            #参考https://www.kancloud.cn/yunye/twig-cn/159459
            \Twig_Autoloader::register();
            $loader = new \Twig_Loader_Filesystem(APP.'/views');
            $twig = new \Twig_Environment($loader, array(
                'cache' => LSS.'/log/twig',
                'debug' =>DEBUG
            ));
            $template = $twig->loadTemplate($file);
            $template->display($this->assign ? $this->assign:array());
        }
    }
}